
local ShellExplosion = class("ShellExplosion", require("unity.LuaMonoBehaviour"))

---
---mTankMask LayerMask
---mExplosionParticles ParticleSystem
---mExplosionAudio AudioSource
---mMaxDamage number
---mExplosionForce number
---mMaxLifeTime number
---mExplosionRadius number
---
function ShellExplosion:Awake()
    
end

function ShellExplosion:Start()
    UnityEngine.Object.Destroy (self.gameObject, self.mMaxLifeTime)
end

function ShellExplosion:OnTriggerEnter(other)
    local colliders = UnityEngine.Physics.OverlapSphere (self.transform.position, self.mExplosionRadius, self.mTankMask.value)
    
    for i,c in table.ipairs_Array(colliders) do
        local targetRigidbody = c:GetComponent("Rigidbody")
        if targetRigidbody then
            targetRigidbody:AddExplosionForce (self.mExplosionForce, self.transform.position, self.mExplosionRadius)
            local targetHealth = targetRigidbody:GetLuaComponent("TankHealth")
            if targetHealth then
                local damage = self:CalculateDamage (targetRigidbody.position)
                targetHealth:TakeDamage(damage)
            end
        end
    end
    self.mExplosionParticles.transform.parent = nil
    self.mExplosionParticles:Play()
    self.mExplosionAudio:Play()
    local mainModule = self.mExplosionParticles.main
    UnityEngine.Object.Destroy (self.mExplosionParticles.gameObject, mainModule.duration);
    UnityEngine.Object.Destroy (self.gameObject)
end

function ShellExplosion:CalculateDamage(targetPosition)
    local explosionToTarget = targetPosition - self.transform.position
    local explosionDistance = explosionToTarget.magnitude
    local relativeDistance = (self.mExplosionRadius - explosionDistance) / self.mExplosionRadius
    local damage = relativeDistance * self.mMaxDamage
    damage = Mathf.Max (0, damage)
    return damage
end

return ShellExplosion
